package FrameWork.EventBus;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReflectReceiveHandler implements ReceiveHandler {
    private Object bean;
    private Method method;
    private ScheduleType scheduleType;

    public ReflectReceiveHandler(Object bean,Method method,ScheduleType type){
        ensureValidMethod(method);
        method.setAccessible(true);
        this.bean = bean;
        this.method = method;
        this.scheduleType = type;
    }

    private void ensureValidMethod(Method method){
        assert method.getParameterTypes().length == 1;
        assert IEvent.class.isAssignableFrom(method.getParameterTypes()[0]);
    }

    @Override
    public Object getBean() {
        return bean;
    }

    @Override
    public ScheduleType getScheduleType() {
        return scheduleType;
    }

    @Override
    public void invoke(IEvent event) {
        try {
            method.invoke(bean,event);
        } catch (IllegalAccessException | InvocationTargetException e) {
            System.out.println(bean.getClass().getName()+":"+method.getName()+":error:"+e.getCause());
        }
    }
}
